import React, { useEffect, useRef, useState } from 'react';
import './MediaCallPanel.css';

function MediaCallPanel({ peer, callType, onEndCall, connectionManager }) {
  const localVideoRef = useRef(null);
  const remoteVideoRef = useRef(null);
  const [isMuted, setIsMuted] = useState(false);
  const [isVideoOff, setIsVideoOff] = useState(false);
  const [callDuration, setCallDuration] = useState(0);

  useEffect(() => {
    let durationInterval;

    // Setup stream listeners
    const handleLocalStream = (stream) => {
      if (localVideoRef.current) {
        localVideoRef.current.srcObject = stream;
      }
    };

    const handleRemoteStream = (stream) => {
      if (remoteVideoRef.current) {
        remoteVideoRef.current.srcObject = stream;
      }
    };

    const handleCallEnded = () => {
      onEndCall();
    };

    connectionManager.on('local-stream', handleLocalStream);
    connectionManager.on('remote-stream', handleRemoteStream);
    connectionManager.on('call-ended', handleCallEnded);

    // Set initial streams if already available
    const localStream = connectionManager.getLocalStream();
    const remoteStream = connectionManager.getRemoteStream();

    if (localStream && localVideoRef.current) {
      localVideoRef.current.srcObject = localStream;
    }

    if (remoteStream && remoteVideoRef.current) {
      remoteVideoRef.current.srcObject = remoteStream;
    }

    // Start call duration timer
    durationInterval = setInterval(() => {
      setCallDuration(prev => prev + 1);
    }, 1000);

    return () => {
      clearInterval(durationInterval);

      // Remove event listeners to prevent memory leaks
      connectionManager.off('local-stream', handleLocalStream);
      connectionManager.off('remote-stream', handleRemoteStream);
      connectionManager.off('call-ended', handleCallEnded);

      // Clear video element sources to prevent memory leaks
      if (localVideoRef.current) {
        localVideoRef.current.srcObject = null;
      }
      if (remoteVideoRef.current) {
        remoteVideoRef.current.srcObject = null;
      }
    };
  }, [connectionManager, onEndCall]);

  const toggleMute = () => {
    const localStream = connectionManager.getLocalStream();
    if (localStream) {
      const audioTrack = localStream.getAudioTracks()[0];
      if (audioTrack) {
        audioTrack.enabled = !audioTrack.enabled;
        setIsMuted(!audioTrack.enabled);
      }
    }
  };

  const toggleVideo = () => {
    const localStream = connectionManager.getLocalStream();
    if (localStream) {
      const videoTrack = localStream.getVideoTracks()[0];
      if (videoTrack) {
        videoTrack.enabled = !videoTrack.enabled;
        setIsVideoOff(!videoTrack.enabled);
      }
    }
  };

  const formatDuration = (seconds) => {
    const mins = Math.floor(seconds / 60);
    const secs = seconds % 60;
    return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
  };

  return (
    <div className="media-call-panel">
      <div className="call-header">
        <div className="call-info">
          <div className="call-peer-name">{peer.name || 'Unknown'}</div>
          <div className="call-status">
            {callType === 'video' ? 'Video Call' : 'Voice Call'} - {formatDuration(callDuration)}
          </div>
        </div>
      </div>

      {callType === 'video' ? (
        <div className="video-container">
          <video
            ref={remoteVideoRef}
            className="remote-video"
            autoPlay
            playsInline
            muted={false}
          />
          <video
            ref={localVideoRef}
            className="local-video"
            autoPlay
            playsInline
            muted
          />
        </div>
      ) : (
        <div className="audio-call-container">
          <div className="audio-avatar">
            {(peer.name || 'U').charAt(0).toUpperCase()}
          </div>
          <div className="audio-call-info">
            <h2>{peer.name || 'Unknown'}</h2>
            <p>{formatDuration(callDuration)}</p>
          </div>
        </div>
      )}

      <div className="call-controls">
        <button
          className={`control-btn mute-btn ${isMuted ? 'active' : ''}`}
          onClick={toggleMute}
          title={isMuted ? 'Unmute' : 'Mute'}
        >
          {isMuted ? '🔇' : '🎤'}
        </button>

        {callType === 'video' && (
          <button
            className={`control-btn video-btn ${isVideoOff ? 'active' : ''}`}
            onClick={toggleVideo}
            title={isVideoOff ? 'Turn On Video' : 'Turn Off Video'}
          >
            {isVideoOff ? '📹❌' : '📹'}
          </button>
        )}

        <button className="control-btn end-call-btn" onClick={onEndCall} title="End Call">
          ❌
        </button>
      </div>
    </div>
  );
}

export default MediaCallPanel;
